<?php defined('BASEPATH') || exit('No direct script access allowed');

/**
 * Campaign controller
 */
class Campaign extends Admin_Controller
{
    protected $permissionCreate = 'Post.Campaign.Create';
    protected $permissionDelete = 'Post.Campaign.Delete';
    protected $permissionEdit   = 'Post.Campaign.Edit';
    protected $permissionView   = 'Post.Campaign.View';

    /**
     * Constructor
     *
     * @return void
     */
    public function __construct()
    {
        parent::__construct();
        
        $this->auth->restrict($this->permissionView);
        $this->load->model('post/post_model');
        $this->load->model('post/campaignphoto_model');
        $this->load->model('tags/tags_model');
        $this->load->model('news/newstag_model');
        $this->load->model('news/news_model');
        $this->load->model('channel/channel_model');
        $this->load->model('phone/phone_model');
        $this->lang->load('post');
        
        $this->form_validation->set_error_delimiters("<span class='error'>", "</span>");
        
        Template::set_block('sub_nav', 'campaign/_sub_nav');

        Assets::add_css(array('plugins/ckeditor/samples/css/samples.css',
                            'plugins/ckeditor/samples/toolbarconfigurator/lib/codemirror/neo.css', 
                            'plugins/iCheck/all.css', 
                            'plugins/select2/select2.min.css',
                            'plugins/daterangepicker/daterangepicker-bs3.css',
                            'plugins/datepicker/datepicker3.css'));
        Assets::add_js(array(Template::theme_url('plugins/select2/select2.full.min.js'), 
                            Template::theme_url('plugins/iCheck/icheck.min.js'), 
                            Template::theme_url('plugins/datepicker/bootstrap-datepicker.js'), 
                            Template::theme_url('plugins/ckeditor/ckeditor.js'),
                            Template::theme_url('plugins/ckeditor/samples/js/sample.js'),
                            Template::theme_url('js/plupload-2.1.1/plupload.full.min.js'),
                            Template::theme_url('js/plupload-2.1.1/i18n/zh_CN.js'), 
                            Template::theme_url('js/qiniu.js'),
                            Template::theme_url('plugins/moment/min/moment.min.js'),
                            Template::theme_url('plugins/moment/min/moment-with-locales.min'),
                            Template::theme_url('plugins/daterangepicker/daterangepicker.js'),
                            Template::theme_url('plugins/thickbox/thickbox3.js'),

                            ));
        Assets::add_js('codeigniter-csrf.js');
        Assets::add_module_js('post', 'post.js');	
    }

    /**
     * Display a list of post data.
     *
     * @return void
     */
    public function index($filter = 'all', $offset = 0)
    {
        // Deleting anything?
        if (isset($_POST['delete'])) {
            $this->auth->restrict($this->permissionDelete);
            $checked = $this->input->post('checked');
            if (is_array($checked) && count($checked)) {

                // If any of the deletions fail, set the result to false, so
                // failure message is set if any of the attempts fail, not just
                // the last attempt

                $result = true;
                foreach ($checked as $pid) {
                    $deleted = $this->post_model->delete($pid);
                    if ($deleted == false) {
                        $result = false;
                    }
                }
                if ($result) {
                    Template::set_message(count($checked) . ' ' . lang('post_delete_success'), 'success');
                } else {
                    Template::set_message(lang('post_delete_failure') . $this->post_model->error, 'error');
                }
            }
        }
        $where = "status != 3 and type=2 ";
        //总数目
        $totalTrashNum = $this->news_model->where($where)->count_all();
        Template::set('totalTrashNum', $totalTrashNum);
        //查询出所有项目名称
        $item_name = $this->news_model->where($where." and project_name is not null ")->group_by("project_name")->select("id,author_pic,source_pic,project_name")->find_all();
        Template::set('item_name', $item_name);
        //回收站总数目
        $rubishNum = $this->news_model->where("status = 3 and type=2")->count_all();
        Template::set('rubishNum', $rubishNum);
        //查询所有有效新闻
        $s['type'] = 1;
        if($this->input->get('type')){
            $search_type = $this->input->get('type');
            switch ($search_type) {
                case  4:
                    $where = "status = 3 and type=2";
                    $s['type'] = 4;
                    break;
                case  1:
                    $where = "status != 3 and type=2";
                    $s['type'] = 1;
                    break;
                default:
                    $where = "status != 3 and type=2";
                    $s['type'] = 2;
                    break;
            }
        }
        $postData = $this->input->get();
        if($postData){
            if(isset($postData['project']) && !empty($postData['project'])){
                $cname = $postData['project'];
                $where .= " and project_name like '%".$cname."%'";
                $s['project'] = $cname;
            }
            if(isset($postData['start_date']) && !empty($postData['start_date'])){
                $start_date = $postData['start_date']." 00:00";
                $where .= " and ctime >= '$start_date' ";
                $s['start_date'] = $postData['start_date'];
                if(isset($postData['end_date']) && !empty($postData['end_date'])){
                    $end_date = $postData['end_date']." 23:59";
                    $where .= " and ctime <= '$end_date' ";
                    $s['end_date'] = $postData['end_date'];
                }
            }
        }
        //分页
        $pagerUriSegment = 6;
        $pagerBaseUrl = site_url(SITE_AREA . '/campaign/post/index') . '/';
        
        $limit  = $this->settings_lib->item('site.list_limit') ?: 15;
        $this->load->library('pagination');
        $this->pager['base_url']    = $pagerBaseUrl.$filter."/";
        $this->pager['total_rows']  = $totalTrashNum;
        $this->pager['per_page']    = $limit;
        $this->pager['uri_segment'] = $pagerUriSegment;

        $this->pagination->initialize($this->pager);
        $this->news_model->limit($limit, $offset);
        //获取所有推广文
        $records = $this->news_model->where($where)->order_by("id","desc")->find_all();
        if($records){
            foreach ($records as $key => $value) {
                $records[$key]->tags = $this->newstag_model->tags($value->id);
                //获取分类
                if(isset($records[$key]->tags['tese'])){
                    $newcategory="";
                    foreach ($records[$key]->tags['tese'] as $fkey => $fvalue) {
                        
                            $newcategory .= $fvalue->tag_name."、";
                        }
                            $str_category = substr($newcategory, 0, -3);
                            $records[$key]->fenlei = $str_category;
                    }else{
                        $records[$key]->fenlei = "无";
                    }
                //获取标签
                if(isset($records[$key]->tags['putong'])){
                    $newtag="";
                    foreach ($records[$key]->tags['putong'] as $tkey => $tvalue) {
                        
                            $newtag .= $tvalue->tag_name."、";
                        }
                            $str_tag = substr($newtag, 0, -3);
                            $records[$key]->tags = $str_tag;
                    }else{
                        $records[$key]->tags = "无";
                    }
                //文章类型
                switch ($value->campaign_mode) {
                        case  1:
                            $records[$key]->type = "文章";
                            break;
                        case  2:
                            $records[$key]->type = "图片";
                            break;
                        case  3:
                            $records[$key]->type = "链接";
                            break;
                    }
                //获取渠道
                if(!empty($value->channel)){
                    $tmp2 = $this->channel_model->find($value->channel);
                    $records[$key]->qd = $tmp2->name;
                }
                //分机号数据
                if(empty($value->phone)){
                    $ext_where = array(
                        'building_code'=>$value->building_code,
                        'building_id'=>0,
                        'deleted'=>0
                    );
                    $ext_arr = $this->phone_model->find_all_by($ext_where);
                    if($ext_arr){
                        $tmp_phone = "";
                        $tmp_name = "";
                        foreach ($ext_arr as $k => $v) {
                            $tmp_phone .= $v->number."<br />";
                            $records[$key]->phone = $tmp_phone;//substr($tmp_phone, 0, strlen($tmp_phone)-1);
                            $channel_info = $this->channel_model->find($v->channel_id);
                            $tmp_name .= $channel_info->name."<br />";
                            $records[$key]->qd = $tmp_name;//substr($tmp_name, 0, strlen($tmp_name)-1);
                        }
                    }
                }
                     
            }
        }
    Template::set('ext_arr', $ext_arr);

    Template::set('search', $s);

    Template::set('records', $records);
    //获取所有渠道
    $channels = $this->channel_model->channels();
    Template::set('channels', $channels);

    Template::set('categories', $this->tags_model->categories_news());
        
    Template::set('toolbar_title', lang('post_manage'));

    Template::render();
    }
    
    /**
     * Create a post object.
     *
     * @return void
     */
    public function create()
    {   
        $this->auth->restrict($this->permissionCreate);
        
        if (isset($_POST['save'])) {
            if ($insert_id = $this->save_post()) {
                log_activity($this->auth->user_id(), lang('post_act_create_record') . ': ' . $insert_id . ' : ' . $this->input->ip_address(), 'post');
                Template::set_message(lang('post_create_success'), 'success');

                redirect(SITE_AREA . '/campaign/post');
            }

            // Not validation error
            if ( ! empty($this->post_model->error)) {
                Template::set_message(lang('post_create_failure') . $this->post_model->error, 'error');
            }
        }
        
        //获取推广页标签
        $news_tag = $this->tags_model->tags_news();
        Template::set('news_tag', $news_tag);
        //获取所有渠道
        $channels = $this->channel_model->channels();
        Template::set('channels', $channels);

        Template::set('categories', $this->tags_model->categories_news());

        Template::set('toolbar_title', lang('post_action_create'));

        Template::render();
    }
    /**
     * Allows editing of post data.
     *
     * @return void
     */
    public function edit()
    {
        $id = $this->uri->segment(5);
        if (empty($id)) {
            Template::set_message(lang('post_invalid_id'), 'error');

            redirect(SITE_AREA . '/campaign/post');
        } elseif (isset($_POST['delete'])) {
            $this->auth->restrict($this->permissionDelete);

            if ($this->post_model->delete($id)) {
                log_activity($this->auth->user_id(), lang('post_act_delete_record') . ': ' . $id . ' : ' . $this->input->ip_address(), 'post');
                Template::set_message(lang('post_delete_success'), 'success');

                redirect(SITE_AREA . '/campaign/post');
            }

            Template::set_message(lang('post_delete_failure') . $this->post_model->error, 'error');
        }
        $records = $this->news_model->find($id);
        //$records->whole_url = site_url($records->url);
        $records->pc_imgs = $this->campaignphoto_model->where("new_id = ". $id ." and platform= 1")->find_all();
        $records->mobile_imgs = $this->campaignphoto_model->where("new_id = ". $id ." and platform= 2")->find_all();
        $pic_array_pc = $this->campaignphoto_model->select("id")->where("new_id = ". $id." and platform = 1")->find_all();
        if(!empty($pic_array_pc)){
                    foreach ($pic_array_pc as $key => $value) {
                           $records->pic_array_pc[] = $value->id;
                        }
                 $records->pic_array_pc = json_encode($records->pic_array_pc);       
        }else{
                    $records->pic_array_pc = json_encode("0");
        }
         $pic_array_mobile = $this->campaignphoto_model->select("id")->where("new_id = ". $id." and platform = 2")->find_all();
        if(!empty($pic_array_mobile)){
                    foreach ($pic_array_mobile as $key => $value) {
                           $records->pic_array_mobile[] = $value->id;
                        }
                 $records->pic_array_mobile = json_encode($records->pic_array_mobile);       
        }else{
                    $records->pic_array_mobile = json_encode("0");
        }
        Template::set('post', $records);
        //分机号数据
        $ext_where = array(
                'building_code'=>$records->building_code,
                'building_id'=>0,
                'deleted'=>0
            );
        $ext_arrs = $this->phone_model->find_all_by($ext_where);
        Template::set('ext_arrs', $ext_arrs);


        $url = site_url("news/");
        Template::set('url', $url);
        //获取新闻分类
        $news_cate = $this->tags_model->categories_news();
        //当前新闻的分类和标签
        $cur_news_tag = $this->newstag_model->tags($id);
        $normal_tags = array();
        if(isset($cur_news_tag['putong']) && is_array($cur_news_tag)){
                  foreach ($cur_news_tag['putong'] as $key => $value) {
                        $normal_tags[$key]['tag_id'] = $value->tag_id;
                        $normal_tags[$key]['tag_name'] = $value->tag_name;
                    }
        }
  
         Template::set('normal_tags', $normal_tags);
        if (isset($cur_news_tag['tese']) && is_array($cur_news_tag)) {
            foreach ($cur_news_tag['tese'] as $key => $val) {
                // 分类标签
                if ($val->type == '2') {
                    foreach ($news_cate as $k => $v) {
                        if ($val->tag_id == $v->tag_id) $news_cate[$k]->selected = 1;
                    }
                }
            }
        }
        //获取所有渠道
        $channels = $this->channel_model->channels();
        Template::set('channels', $channels);
        
        Template::set('toolbar_title', lang('news_action_create'));
        //新闻分类
        Template::set('categories', $news_cate);

        Template::set('toolbar_title', lang('news_edit_heading'));
        Template::render();
    }

    public function save(){

        $postData = $this->input->post();
        //dump($postData);exit();
        if($postData) {
            //普通模式
            $data['title'] = isset($postData['title']) ? $postData['title'] : "";
            $data['content'] = isset($postData['stem'])?$postData['stem']:"";
            $data['source_pic'] = isset($postData['img_url'])?$postData['img_url']:"";
            $data['type'] = isset($postData['type'])?$postData['type']:2;//1新闻2推广文
            $action = isset($postData['action'])?$postData['action']:1;//1发布动作 2暂存动作
            $data['url'] = isset($postData['link_url'])?$postData['link_url']:"";
            $data['zhaiyao'] = isset($postData['zhaiyao'])?$postData['zhaiyao']:"";
            $data['building_code'] = isset($postData['building_code'])?$postData['building_code']:"";
            $data['channel'] = isset($postData['channel'])?$postData['channel']:"";
            $data['phone'] = isset($postData['phone_num'])?$postData['phone_num']:"";
            //type1 新增 2 修改
            $type = isset($postData['ac_type'])?$postData['ac_type']:1;
            $data['city'] = isset($postData['city'])?$postData['city']:0;
            $id = isset($postData['id'])?$postData['id']:"";
            $data['is_campaign'] =1;
            //按钮开关
            $data['phone_switch'] = isset($postData['show_phone'])?$postData['show_phone']:0;
            $data['yuyue_switch'] = isset($postData['show_yuyue'])?$postData['show_yuyue']:0;
            $data['hx_switch'] = isset($postData['show_hx'])?$postData['show_hx']:0;
            //推广文模式
            $data['campaign_mode'] = isset($postData['mode'])?$postData['mode']:0;
            //外部链接
            $data['target_link'] = isset($postData['target_link'])?$postData['target_link']:"";
            //项目名称
            $data['project_name'] = isset($postData['project_name'])?$postData['project_name']:"";
            //渠道名称（弃用）
            $data['channel'] = isset($postData['channel'])?$postData['channel']:0;
            //渠道和分机号
            $plats = isset($postData['plats'])?$postData['plats']:"";
            $channels = isset($postData['channels'])?$postData['channels']:"";
            $exts = isset($postData['exts'])?$postData['exts']:"";
            if(!empty($exts[0])){
                if(!empty($exts)){
                    $building_code = $data['building_code'];
                    foreach ($exts as $key => $val) {
                        if ($this->phone_model->where("number = {$val} AND deleted = 0 AND building_code != '$building_code'")->count_all()) {
                            echo json_encode(['code'=>3,'msg'=>"分机号已经存在"]); exit();
                        }
                    }
                    if($id && $type == 2){//修改操作删除之前的分机号
                        $edit_del_where = array(
                            'building_code'=>$building_code,
                            'building_id'=>0,
                        );
                       $this->phone_model->delete_where($edit_del_where);
                       //$sql = $this->db->last_query();
                       //echo $sql;exit();
                    }
                }
                if(!empty($channels)){
                     foreach ($channels as $key => $value) {
                        if(!empty($exts[$key]) && !empty($data['building_code'])){
                            $channels_data[$key]['building_id'] = 0;
                            $channels_data[$key]['platform'] = $plats[$key];
                            $channels_data[$key]['number'] = $exts[$key];
                            $channels_data[$key]['channel_id'] = $value;
                            $channels_data[$key]['building_code'] = $data['building_code'];
                        }
                    }
                    $this->phone_model->insert_batch($channels_data);
                }
            }else{
                $building_code = $data['building_code'];
                $edit_del_where = array(
                            'building_code'=>$building_code,
                            'building_id'=>0,
                        );
                $this->phone_model->delete_where($edit_del_where);
            }
            if($action == 2){//点击确定按钮
                $data['status'] = isset($postData['status'])?$postData['status']:"";
            }else{//直接点击发布按钮
                $data['status'] = 2;
                $data['publish_time']=date("Y-m-d H:i",time());
            }
            if($id && $type == 2){
                $res = $this->news_model->update($id,$data);
                $this->campaignphoto_model->delete_where("new_id=".$id);
            }else{
                $data['ctime'] = date("Y-m-d H:i",time());
                $id = $this->news_model->insert($data);
            }
             //图片模式存图片
            if($data['campaign_mode'] == 2){
                $pc_data = isset($postData['pc_url'])?$postData['pc_url']:0;
                if(!empty($pc_data)){
                         foreach ($pc_data as $key => $value) {
                            $pc_info[$key]['url'] = $value;
                            $pc_info[$key]['title'] = "";
                            $pc_info[$key]['desc'] = "";
                            $pc_info[$key]['platform'] = 1;
                            $pc_info[$key]['new_id'] = $id;
                            $pc_info[$key]['status'] = 1;
                        }
                        $this->campaignphoto_model->insert_batch($pc_info);
                }

                $mobile_data = isset($postData['mobile_url'])?$postData['mobile_url']:0;
                if(!empty($mobile_data)){
                        foreach ($mobile_data as $key => $value) {
                            $mobile_info[$key]['url'] = $value;
                            $mobile_info[$key]['title'] = "";
                            $mobile_info[$key]['desc'] = "";
                            $mobile_info[$key]['platform'] = 2;
                            $mobile_info[$key]['new_id'] = $id;
                            $mobile_info[$key]['status'] = 1;
                        }
                        $this->campaignphoto_model->insert_batch($mobile_info);
                }
            }           
            if($id){
                    $this->newstag_model->delete_where("news_id=".$id);  
                //加分类
                $cate = isset($postData['cate'])?$postData['cate']:"";
                if($cate){
                    $cateArr = explode(",", $cate);
                    $this->newstag_model->addCategories($id, $cateArr,2);
                }
                //加标签
                $tags = isset($postData['tags'])?$postData['tags']:"";
                //dump($tags);exit();
                if($tags){
                    $this->newstag_model->addNewsTags($id, 1,$tags);
                }
                echo json_encode(['code'=>1,'msg'=>"新增成功"]); exit();
            }else{
                echo json_encode(['code'=>2,'msg'=>"新增失败"]); exit();
            }
        }

    }

        //更改新闻状态
    public function changestatus(){
         $id = $this->uri->segment(5);
         $type= $this->uri->segment(7);
        if($id && $type){
            if($type==1){
                $data['status'] = 3;
                $res= $this->news_model->update($id, $data);
                //dump($res);exit();
                redirect(SITE_AREA . '/campaign/post');
            }
            if($type ==2){
                $data['status'] = 1;
                $this->news_model->update($id, $data);
                redirect(SITE_AREA . '/campaign/post');
            }
          if($type ==3){
                $data['status'] = 5;
                $this->news_model->update($id, $data);
                redirect(SITE_AREA . '/campaign/post');
            }
        }

    }
    //--------------------------------------------------------------------------
    // !PRIVATE METHODS
    //--------------------------------------------------------------------------

    /**
     * Save the data.
     *
     * @param string $type Either 'insert' or 'update'.
     * @param int    $id   The ID of the record to update, ignored on inserts.
     *
     * @return boolean|integer An ID for successful inserts, true for successful
     * updates, else false.
     */
    // private function save_post($type = 'insert', $id = 0)
    // {
    //     if ($type == 'update') {
    //         $_POST['id'] = $id;
    //     }

    //     // Validate the data
    //     $this->form_validation->set_rules($this->post_model->get_validation_rules());
    //     if ($this->form_validation->run() === false) {
    //         return false;
    //     }

    //     // Make sure we only pass in the fields we want
        
    //     $data = $this->post_model->prep_data($this->input->post());

    //     // Additional handling for default values should be added below,
    //     // or in the model's prep_data() method
        

    //     $return = false;
    //     if ($type == 'insert') {
    //         $id = $this->post_model->insert($data);

    //         if (is_numeric($id)) {
    //             $return = $id;
    //         }
    //     } elseif ($type == 'update') {
    //         $return = $this->post_model->update($id, $data);
    //     }

    //     return $return;
    // }
}